#!/usr/bin/env python
""" This is a CLI script for awarding a single badge to a single person.

The intent is to use it to batch award a badge to a list of people.
"""

import __main__
__main__.__requires__ = __requires__ = ["tahrir-api", "sqlalchemy>=0.7"];
import pkg_resources
pkg_resources.require(__requires__)

import argparse
import transaction
import sys

from tahrir_api.dbapi import TahrirDatabase

import fedmsg
import fedmsg.config

import fedbadges.utils


def parse_args():
    parser = argparse.ArgumentParser(__doc__)
    parser.add_argument('--user', default=None, help="A FAS username")
    parser.add_argument('--badge', default=None, help="A badge id")
    args = parser.parse_args()
    if not args.user:
        print "You must specify a FAS username."
        sys.exit(1)
    if not args.badge:
        print "You must specify a badge id."
        sys.exit(1)
    return args


def initialize():
    fm_config = fedmsg.config.load_config()
    fm_config['cert_prefix'] = 'fedbadges'
    fm_config['name'] = 'relay_inbound'
    fm_config['active'] = True
    fedmsg.init(**fm_config)
    uri = fm_config['badges_global']['database_uri']
    tahrir = TahrirDatabase(
        uri,
        notification_callback=fedbadges.utils.notification_callback,
    )
    return tahrir


def main(tahrir, nickname, badge_id):
    person = tahrir.get_person(nickname=nickname)
    badge = tahrir.get_badge(badge_id)

    if not person:
        print "No such person %r" % nickname
        sys.exit(1)

    if not badge:
        print "No such badge %r" % badge_id
        sys.exit(1)

    already_has_it = [assertion.person for assertion in badge.assertions]

    if person in already_has_it:
        print "%r already has the %r badge..." % (nickname, badge_id)
        return

    print person.nickname, "totally gets the %r badge." % badge_id
    try:
        transaction.begin()
        tahrir.add_assertion(badge.id, person.email, None)
        transaction.commit()
    except Exception as e:
        transaction.abort()
        print "Failure:", e


if __name__ == '__main__':
    args = parse_args()
    tahrir = initialize()
    main(tahrir, args.user, args.badge)
